<template>
  <div class="app-container">
    <div style="background: #FFFFFF;padding: 0.625rem;">
      <div style="margin-bottom: 0.625rem;height: 2.5rem;">
        <el-button v-permission="'wechatmenu@add'" class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate">
          新增
        </el-button>
        <el-tooltip class="item" effect="dark" content="展开/折叠" placement="top">
          <el-button circle class="filter-item" style="float: right;" plain icon="el-icon-sort" @click="expandTable" />
        </el-tooltip>
        <el-button circle style="float: right;" icon="el-icon-refresh" @click="getList" />
        <el-tooltip class="item" effect="dark" content="同步至公众号" placement="top">
          <el-button v-permission="'wechatmenu@syncdata'" circle type="success" style="float: right;" icon="el-icon-upload2" @click="syncDataMenu" />
        </el-tooltip>
      </div>
      <el-table
        v-if="refreshTable"
        ref="dataTable"
        v-loading="listLoading"
        :data="list"
        :header-cell-style="{background:'#eee',color:'#606266'}"
        fit
        highlight-current-row
        style="width: 100%;"
        row-key="id"
        show-header
        :default-expand-all="tableExpandAll"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      >

        <el-table-column label="菜单名称" width="140px" align="left">
          <template slot-scope="{row}">
            <span class="link-type" @click="handleUpdate(row)">{{ row.title }}</span>
          </template>
        </el-table-column>
        <el-table-column label="类型" width="80px" align="center">
          <template slot-scope="{row}">
            <span v-if="row.type==='view'">
              <el-tag effect="dark" type="success">网页</el-tag>
            </span>
            <span v-if="row.type==='click'">
              <el-tag effect="dark" type="">点击</el-tag>
            </span>
            <span v-if="row.type==='miniprogram'">
              <el-tag effect="dark" type="warning">小程序</el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="网页/链接" width="260px" align="left">
          <template slot-scope="{row}">
            <span>{{ row.url }}</span>
          </template>
        </el-table-column>
        <el-table-column label="小程序AppId" width="130px" align="left">
          <template slot-scope="{row}">
            <span>{{ row.appid }}</span>
          </template>
        </el-table-column>
        <el-table-column label="小程序路径" width="130px" align="left">
          <template slot-scope="{row}">
            <span>{{ row.pagepath }}</span>
          </template>
        </el-table-column>
        <el-table-column label="排序" width="60px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.sort }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" min-width="155px">
          <template slot-scope="{row}">
            <span>{{ row.created_at }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="130" class-name="small-padding fixed-width">
          <template slot-scope="{row,$index}">
            <el-button v-permission="'wechatmenu@edit'" title="编辑" type="primary" icon="el-icon-edit" circle @click="handleUpdate(row)" />
            <el-button v-if="row.status!=='deleted'" v-permission="'wechatmenu@del'" title="删除" icon="el-icon-delete" circle type="danger" @click="handleDelete(row,$index)" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="60%">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="80px">
        <div class="el-col el-col-24">
          <el-form-item label="父级菜单" prop="parent_id">
            <el-cascader
              v-model="temp.parent_id"
              style="width:90%"
              :options="cascaderData"
              clearable
              @change="cascaderCheck"
            />
          </el-form-item>
        </div>
        <div class="el-col el-col-24">
          <el-form-item label="菜单类型" prop="type">
            <el-radio-group v-model="temp.type" @input="menuType">
              <el-radio-button label="view">网页类型</el-radio-button>
              <el-radio-button label="miniprogram">小程序类型</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </div>
        <div class="el-col el-col-24">
          <el-form-item label="菜单名称" prop="title">
            <el-input v-model="temp.title" placeholder="请输入2-60字符的菜单名称" />
          </el-form-item>
        </div>
        <div class="el-col el-col-24">
          <el-form-item label="链接" prop="url">
            <el-input v-model="temp.url" placeholder="请输入2-1020字符的链接" />
          </el-form-item>
        </div>
        <div v-if="isShowType" class="el-col el-col-12">
          <el-form-item label="AppId" prop="appid">
            <el-input v-model="temp.appid" placeholder="请输入小程序AppId" />
          </el-form-item>
        </div>
        <div v-if="isShowType" class="el-col el-col-12">
          <el-form-item label="页面路径" prop="pagepath">
            <el-input v-model="temp.pagepath" placeholder="请输入小程序的页面路径" />
          </el-form-item>
        </div>
        <div class="el-col el-col-24">
          <el-form-item label="排序" prop="url">
            <el-input v-model="temp.sort" placeholder="0" />
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-switch-button" @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button icon="el-icon-s-promotion" type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getData, getAll, createMenu, updateMenu, delMenu, syncData } from '@/api/wechat-menu'
import waves from '@/directive/waves' // waves directive
import permission from '@/directive/permission'
import { parseTime } from '@/utils'

const calendarTypeOptions = [
  { key: '0', display_name: '正常' },
  { key: '1', display_name: '禁用' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'PermissionRules',
  // components: { Pagination },
  directives: { waves, permission },
  filters: {
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      list: [],
      listLoading: true,
      calendarTypeOptions,
      tableExpandAll: false,
      cascaderData: [],
      statusOptions: ['启用', '禁用'],
      refreshTable: true,
      temp: {
        id: undefined,
        title: '',
        parent_id: 0,
        type: '',
        url: '',
        appid: '',
        pagepath: '',
        sort: 0
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        title: [{ required: true, message: '菜单名称必填', trigger: 'change' }],
        permission_mark: [{ required: true, message: '权限标识必填', trigger: 'change' }],
        module: [{ required: true, message: '模块必选', trigger: 'change' }]
      },
      isShowSwitch: '',
      isShowType: false
    }
  },
  created() {
    this.getList()
    this.getAll()
  },
  methods: {
    expandTable() {
      this.refreshTable = false
      this.tableExpandAll = !this.tableExpandAll
      this.$nextTick(() => {
        this.refreshTable = true
      })
    },
    menuType: function(params) {
      this.isShowType = params === 'miniprogram'
    },
    getAll() {
      getAll().then(response => {
        this.cascaderData = response.data
      })
    },
    getList() {
      this.listLoading = true
      getData(this.listQuery).then(response => {
        this.list = response.data
        this.listLoading = false
      })
    },
    cascaderCheck: function(data) {
      this.temp.parent_id = data[data.length - 1]
      this.temp.level = data.split('-')
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        title: '',
        parent_id: 0,
        type: '',
        url: '',
        appid: '',
        pagepath: '',
        sort: 0
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.listLoading = true
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.listLoading = false
          createMenu(this.temp).then(response => {
            this.getList()
            this.getAll()
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '新增成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.isShowType = this.temp.type === 'miniprogram'
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.listLoading = true
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          delete tempData.value
          this.listLoading = false
          updateMenu(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.getList()
            this.getAll()
            this.$notify({
              title: 'Success',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    syncDataMenu() {
      this.$confirm('此操作将菜单同步至微信公众号 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.openFullScreen()
        syncData().then(() => {
          this.$notify({
            title: 'Success',
            message: '同步成功',
            type: 'success',
            duration: 2000
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },
    openFullScreen() {
      const loading = this.$loading({
        lock: true,
        text: '数据同步中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      setTimeout(() => {
        loading.close()
      }, 2000)
    },
    handleDelete(row, index) {
      this.$confirm('此操作将该数据永久删除成功, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const tempData = {}
        tempData.ids = row.id
        delMenu(tempData).then(() => {
          this.dialogFormVisible = false
          this.$notify({
            title: 'Success',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.list.splice(index, 1)
          this.getList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>

<style>
  .filter-item{
    margin-right: 0.3125rem;
  }
</style>
